<template>
  <el-form :model="detailForm" :rules="rules" ref="detailForm" :inline="false"
           :label-position="labelPosition" :class="isEdit?'':'formItem'"
  >
    <!-- 投保要求区域 -我司购买/非店保 -->
    <el-card class="box-card" shadow="never">
      <div slot="header" class="header-card">
        <span class="header-card-title">投保要求</span>
      </div>
      <el-row :gutter="24">
        <el-col :span="8" v-if="isShow">
          <el-form-item label="禀议内供应商:">
            <el-input v-if="isEdit" v-model="detailForm.rentInsuranceCompany" disabled></el-input>
            <span v-else>{{ detailForm.rentInsuranceCompany }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="isShow">
          <el-form-item label="投保渠道:">
            <el-select v-model="detailForm.insuranceChannels" v-if="isEdit" style="width: 100%;" disabled>
              <el-option v-for="v in dict.type.insurance_channels" :label="v.label" :key="v.value"
                         :value="Number(v.value)">
              </el-option>
            </el-select>

            <span v-else>{{ selectDictLabel(dict.type.insurance_channels, detailForm.insuranceChannels) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="被保险人:" v-if="isShow" prop="syxInsuredName">
            <el-input v-model="detailForm.syxInsuredName" maxlength="50" v-if="isEdit"
                      placeholder="请输入被保险人"></el-input>
            <span v-else>{{ detailForm.syxInsuredName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8" v-if="isShow">
          <el-form-item label="保险起期:" prop="syxExpectBeginTime">
            <el-date-picker v-model="detailForm.syxExpectBeginTime" type="date" placeholder="请选择保险起期"
                            v-if="isEdit" value-format='yyyy-MM-dd' style="width: 100%;">
            </el-date-picker>
            <span v-else>{{ detailForm.syxExpectBeginTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="isShow">
          <el-form-item label="保险性质:" prop="syxInsuranceType" v-if="isShow">
            <el-select v-model="detailForm.syxInsuranceType" v-if="isEdit" style="width: 100%;"
                       placeholder="请选择保险性质">
              <el-option label="运营" value="1">
              </el-option>
              <el-option label="非运营" value="2">
              </el-option>
            </el-select>

            <span v-else>{{

                detailForm.syxInsuranceType == 1 ? '运营' : detailForm.syxInsuranceType == 2 ? '非运营' : ''
              }}</span>

          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col v-if="isShow">
          <el-form-item label="特殊事项说明:" prop="syxRemark">
            <el-input v-if="isEdit" type="textarea" v-model="detailForm.syxRemark" maxlength="500"
                      placeholder="请输入特殊事项说明"></el-input>
            <span v-else>{{ detailForm.syxRemark }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col style="margin-bottom: 8px;">
          <div style="padding-bottom:8px;font-size: 16px;">保险套餐</div>
          <el-table :data="detailForm.businessList" border size='mini'>
            <el-table-column align="center" type="index" label="序号"></el-table-column>
            <el-table-column label="操作" v-if="detailForm.addProStatus == 1" width="100">
              <template #default="{row, $index}">
                <e-button type="text" v-if="row.boole" icon="eel-icon-plus"
                          @click="handleDle($index)">删除
                </e-button>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="insuranceProName" label="商业险种"></el-table-column>

            <el-table-column align="center" prop="insuranceQuota" label="保额/万元" v-if="detailForm.addProStatus == 2">
              <template slot-scope="{row,$index}">
                <span v-if="typeof row.insuranceQuota === 'number'">
                  {{ format_thousand(row.insuranceQuota) || '--' }}
                </span>
                <span v-else>
                  {{ row.insuranceQuota }}
                </span>
              </template>
            </el-table-column>

            <el-table-column align="center" prop="insuranceQuota" label="保额/万元" v-if="detailForm.addProStatus == 1">
              <template slot-scope="{row,$index}">
                <el-input v-model="row.insuranceQuota" v-if="isEdit"
                          placeholder="请输入保额/万元"
                          @change="changeTable(row, $index, 'insuranceQuota')"
                          size="mini"/>
                <span v-else>{{ row.insuranceQuota }}</span>
              </template>
            </el-table-column>
            <template v-slot:append
                      v-if="detailForm.addProStatus == 1 &&
                      detailForm.businessList.length !== dict.type.insurance_project.length">
              <div class="flex-xy-center" style="height: 40px">
                <div style="display: flex">
                  <e-button type="text" style="margin-right: 20px" icon="eel-icon-plus"
                            v-if="insuranceProName !== ''"
                            @click="addDecoration">添加
                  </e-button>
                  <el-select v-model="insuranceProValue" v-if="isEdit" placeholder="请选择商业险种"
                             style="width: 100%;" @change="handleInsuranceProName">
                    <el-option v-for="v in dict.type.insurance_project" :key="v.value" :label="v.label"
                               :disabled="v.disabled"
                               :value="v.value">
                    </el-option>
                  </el-select>
                </div>

              </div>
            </template>
          </el-table>

        </el-col>

      </el-row>
    </el-card>
  </el-form>
</template>

<script>
export default {
  mame: 'divisionPurchase',// - 投保要求区域 -我司购买/非店保
  dicts: ['insurance_channels', 'insurance_project'],


  props: {
    value: {
      type: Object,
      default: {}
    },
    state: {
      type: String,
      default: "",
    }
  },

  computed: {
    detailForm: {
      get() {
        let that = this
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key)
          },
          set(target, key, value) {
            that.handleData(key, value)
            that.$emit('input', {...target, [key]: value})
            return true
          }
        })
        return proxy
      }
    },
    labelPosition() {
      if (this.state === 'write') {
        return 'top'
      } else {
        return 'right'
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool
    }
  },

  watch: {},
  data() {
    return {
      isShow: true,
      obj: {},
      rules: {
        //商业险信息
        syxInsuredName: [{required: this.state === 'write', message: '请输入被保险人', trigger: 'blur'}],
        syxExpectBeginTime: [{required: this.state === 'write', message: '请选择商业险起保日', trigger: 'change'}],
        syxInsuranceType: [{required: this.state === 'write', message: '请选择商业险性质', trigger: 'change'}],
      },
      insuranceProName: '',
      insuranceProValue: '',
    };
  },
  created() {
  },
  mounted() {
  },
  methods: {
    handleInsuranceProName(val) {
      let index = this.detailForm.businessList.findIndex(a => Number(a.insuranceProCode) === Number(val))
      if (index !== -1) {
        this.insuranceProName = ''
        this.insuranceProValue = ''
        this.$message({
          message: '商业险种已有，请重新选择',
          type: 'warning'
        });
        return
      }
      let str = this.dict.type.insurance_project.map(a => {
        if (val == a.value) {
          return a.label
        }
      }).filter(a => a)[0]
      this.insuranceProName = str
      this.insuranceProValue = val
    },

    addDecoration() {

      let obj = {
        createBy: null,
        createTime: null,
        delFlag: null,
        id: null,
        insuranceId: null,
        insuranceManageId: null,
        insurancePrice: null,
        insuranceProCode: Number(this.insuranceProValue),
        insuranceProName: this.insuranceProName,
        insuranceQuota: "",
        updateBy: null,
        updateStatus: null,
        updateTime: '',
        boole: true
      }
      this.detailForm.businessList.push(obj)
      this.insuranceProName = ''
      this.insuranceProValue = ''
      this.$forceUpdate()
    },

    handleDle(index) {
      this.detailForm.businessList.splice(index, 1)
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            this.locateToErr()
            reject();
          }
        });
      })
    },
    locateToErr() {

      this.$nextTick(() => {
        let isError = document.getElementsByClassName('is-error')
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: 'center',
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: 'smooth',
        })
      })
    },
    // 店保金额格式
    changeTable(row, key, field) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/

      if (msg.test(Number(row[field]))) {
        if (Number(row[field]) >= 0) {
          let _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
          row[field] = _value
        } else {
          row[field] = ""
        }
      } else {
        row[field] = ""
      }
      // this.addAmountNun = this.addAmount(this.detailForm.carMaintainProjectList, 'price')


    },

    changeAmount(str) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/
      if (!msg.test(this.detailForm[str])) {
        this.detailForm[str] = ""
      } else {
        this.detailForm[str] = this.detailForm[str].toString().match(/^\d+(?:\.\d{0,2})?/)[0]
      }
    },

    //取消表单效验
    handleClearValidate() {
      //this.$refs.detailForm.clearValidate()
    },
    valid() {
      return new Promise((resolve) => {
        this.$refs.detailForm.validate((valid) => {
          resolve(valid);
        });
      })
    },

    handleData(key, value) {
      this.value.insuranceVoList.forEach(item => {
        if (typeof (item) !== "string") {
          item[key] = value
        } else {
          item[key] = value
        }

      })
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/cwgd/formScss.scss";
</style>


